import React, { PureComponent } from 'react'
import {
  Form, Input, Select, Radio, Checkbox, Tooltip, Button, InputNumber, Modal, Spin,
  message, TreeSelect, Tabs, Popover, AutoComplete, Row, Col,
} from 'antd'
import { history } from '@umijs/max'
import list2tree from 'list2tree'
import sqlFormatter from 'sql-formatter'
import styles from './index.less'
import { regExp } from '@/utils/regExp.js'
import {
  getHashParameterByName,
} from '@/utils/helper'
import {
  getDatabasesByDsType, onlinePreviewData, getCreateTableSql, executeCreateTableSql,
  getTables, getTopic, getDirList, previewDataForMq, onlineInsert, onlineSchema,
} from './api'
import {
  CreateDiffEditor, ProTable,
} from '@/components'

const getNavTreeDataFunc = list2tree({
  idKey: 'id',
  parentIdKey: 'pid',
  newKey: {
    key: 'id',
    value: 'id',
    title: 'dirName',
  },
})

const lenRe = regExp.proName(1, 128)

const { Option } = Select
const { TextArea } = Input
const { TabPane } = Tabs
const { Item, List } = Form

class DataSource extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      dirId: getHashParameterByName('dirId'),
      infoCase: 1,
      sourceDs: null,
      targetDs: null,
      targetTables: null,
      sourceTables: null,
      spinning: false,
      scripts: '',
      sourceDsId: '',
      sourceTableOrTopic: '',
      fieldSuggestion: [],
      previewData: {
        columns: [],
        data: [],
      },
      isInfluxDBNew: true,
      sourceDsType: null,
      jsScript: '',
      functionStr: `function parseJson(inputParam) {
  // inputParam为返回报文的JSON字符串
  // var dataObj = JSON.parse(inputParam)
  // var result=[['参数1','参数2','...']]  // 定义参数名
  // var 参数1 = dataObj.errno //输入根节点数据
  // for(i=0; i < dataObj.xx.length; i++) {  // 此处输入处理逻辑,以循环遍历为例
  //    var arr = []
  //    var 参数2 = dataObj.xx[0].yy  // 输入叶子节点数据
  //    arr.push(参数1)
  //    arr.push(参数2)
  //    result.push(arr)
  // }
  // return result
}`,
      velocity: `$iot.setStorageGroupDirect($IOT_DATA_MODEL,"root.ninggang")
$iot.setDeviceIdFromJson($IOT_DATA_MODEL,"&.sn")
$iot.setTimestampFromJson($IOT_DATA_MODEL,"&.time")
#set($result=$iot.setMeasurementFromJson($IOT_DATA_MODEL,"&.data.YS_YS.*","id","value"))`,
    }
    this.form = React.createRef()
    this.editorJsEditId = `${Math.random()}`
    this.customEditorRef = React.createRef()
  }

  componentDidMount() {
    this.getDatabasesByDsType(0)
    this.getDatabasesByDsType(1)
    this.getDirList()
    this.form && this.form.current.setFieldsValue({
      dirId: this.state.dirId || 0,
    })
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.data !== this.props.data) {
      const data = nextProps.data
      if (!data.id) return
      this.form && this.form.current.setFieldsValue({
        taskName: data.taskName,
        sourceDsId: `${data.sourceDsId}_${data.sourceDsType}`,
        targetDsId: `${data.targetDsId}_${data.targetDsType}`,
        targetTableOrTopic: data.targetTableOrTopic,
        sourceTableOrTopic: data.sourceTableOrTopic,
        start: data.start,
        dirId: data.dirId,
        useJsFlag: String(data.useJsFlag ? data.useJsFlag : 0),
        fieldExpressRequests: data.fieldExpressRequests,
        tableData: data.tableData,
      })
      this.setState({
        sourceDsId: data.sourceDsId,
        sourceDsType: data.sourceDsType,
        targetDsId: data.targetDsId,
        targetDsType: data.targetDsType,
        sourceTableOrTopic: data.sourceTableOrTopic,
        jsScript: data.jsContent,
        useJsFlag: String(data.useJsFlag ? data.useJsFlag : 0),
      })
      this.onlineSchema(0, data.sourceDsId, data.sourceDsType, data.sourceSchema)
      this.onlineSchema(1, data.targetDsId, data.targetDsType, data.targetSchema)
    }
  }

  getDirList = () => {
    getDirList().then((res) => {
      this.setState({
        treeData: getNavTreeDataFunc(res.data || []),
      })
    }, (error) => {
    })
  }

  getDatabasesByDsType = (direction) => {
    getDatabasesByDsType({ direction }).then((data) => {
      if (direction) {
        this.setState({
          targetDs: data,
        })
      } else {
        this.setState({
          sourceDs: data,
        })
      }
    })
  }

  getTables = (direction, dsId, type, schema) => {
    this.setState({
      spinning: true,
    })
    if (type === 'Kafka') {
      getTopic({ dsId, schema: schema || null }).then((res) => {
        this.setState({
          spinning: false,
        })
        if (res.status === 200) {
          if (direction) {
            this.setState({
              targetTables: res.data,
            })
          } else {
            this.setState({
              sourceTables: res.data,
            })
          }
        } else if (direction) {
          this.setState({
            targetTables: [],
          })
        } else {
          this.setState({
            sourceTables: [],
          })
        }
      })
    } else if (type !== 'MQTT') {
      getTables({ dsId, schema: schema || null, direction }).then((res) => {
        this.setState({
          spinning: false,
        })
        if (res.status === 200) {
          if (direction) {
            this.setState({
              targetTables: res.data,
            })
            if (this.props.data.targetDsType === 'InfluxDB') {
              if (res.data.find((item) => item.tableName === this.props.data.targetTableOrTopic)) {
                this.setState({
                  isInfluxDBNew: true,
                })
                this.form.current?.setFieldsValue({ isInfluxDBNew: true })
              } else {
                this.setState({
                  isInfluxDBNew: false,
                })
                this.form.current?.setFieldsValue({ isInfluxDBNew: false })
              }
            }
          } else {
            this.setState({
              sourceTables: res.data,
            })
          }
        } else if (direction) {
          this.setState({
            targetTables: [],
          })
        } else {
          this.setState({
            sourceTables: [],
          })
        }
      })
    }
  }

  valuesChange = (value, allValues) => {
    const key = Object.keys(value)[0]
    if (key === 'sourceDsId') {
      if (!allValues.sourceDsId) return
      const arr = allValues.sourceDsId.split('_')
      this.setState({
        sourceDsId: arr[0],
        sourceDsType: arr[1],
        sourceSchema: [],
        sourceTables: [],
        useJsFlag: '',
      }, () => {
        this.onlineSchema(0, arr[0], arr[1])
      })
      this.form.current.setFieldsValue({
        fieldExpressRequests: [{
          fieldName: '',
          fieldExpress: '',
        }],
        useJsFlag: '0',
        tableData: null,
        sourceTable: null,
        sourceSchema: null,
        sourceTableOrTopic: '',
      })
    } else if (key === 'targetDsId') {
      if (!allValues.targetDsId) return
      const arr = allValues.targetDsId.split('_')
      this.form.current.setFieldsValue({
        targetTable: null,
        targetSchema: null,
        targetTableOrTopic: '',
      })
      this.setState({
        targetDsId: arr[0],
        targetDsType: arr[1],
        targetSchema: [],
        targetTables: [],
        schema: '',
      }, () => {
        this.onlineSchema(1, arr[0], arr[1])
      })
    } else if (key === 'sourceTableOrTopic') {
      this.setState({
        sourceTableOrTopic: allValues.sourceTableOrTopic,
      })
    } else if (key === 'sourceSchema') {
      this.form.current.setFieldsValue({
        // sourceTable: null,
        sourceTableOrTopic: null,
      })
      this.getTables(0, this.state.sourceDsId, this.state.sourceDsType, allValues.sourceSchema)
    } else if (key === 'targetSchema') {
      this.form.current.setFieldsValue({
        // targetTable: null,
        targetTableOrTopic: null,
      })
      this.setState({
        schema: allValues.targetSchema,
      })
      this.getTables(1, this.state.targetDsId, this.state.targetDsType, allValues.targetSchema)
    }
  }

  onlineSchema = (type, dsId, dsType, schema) => {
    this.setState({
      spinning: true,
    })
    onlineSchema({ dsId, dsType }).then((res) => {
      if (res.status === 200) {
        if (res.data && res.data.length) {
          if (type) {
            this.setState({
              targetSchema: res.data,
            }, () => {
              if (schema) {
                this.form.current.setFieldsValue({
                  targetSchema: schema,
                })
                this.getTables(type, dsId, dsType, schema)
              }
            })
          } else {
            this.setState({
              sourceSchema: res.data,
            }, () => {
              if (schema) {
                this.form.current.setFieldsValue({
                  sourceSchema: schema,
                })
                this.getTables(type, dsId, dsType, schema)
              }
            })
          }
        } else {
          this.getTables(type, dsId, dsType)
        }
      } else {
        message.error(res.msg)
      }
      this.setState({
        spinning: false,
      })
    })
  }

  // eslint-disable-next-line consistent-return
  onlinePreviewData = () => {
    const { sourceDsId, sourceTableOrTopic } = this.state
    if (!sourceDsId || !sourceTableOrTopic) return message.error('数据来源或数据表不能为空')
    onlinePreviewData({ dsId: sourceDsId, tableName: sourceTableOrTopic }).then((res) => {
      this.setState({
        dataShows: true,
      })
      if (res.status === 200) {
        if (!res.data) return
        const data = []
        const columns = []
        res.data.fieldNameList
          && res.data.fieldNameList.map((name, i) => {
            columns.push({
              title: name,
              dataIndex: name,
              key: name,
              width: 100,
            })
          })
        res.data.dataList
          && res.data.dataList.map((arr, key) => {
            const dataObj = { key }
            res.data.fieldNameList
              && res.data.fieldNameList.map((name, i) => {
                dataObj[name] = arr[i]
              })
            data.push(dataObj)
          })
        this.setState({
          previewData: {
            columns,
            data,
          },
        })
      } else {
        message.warning(res.msg)
      }
    })
  }

  // eslint-disable-next-line consistent-return
  getCreateTableSql = () => {
    const {
      sourceDsId, sourceTableOrTopic, targetDsId, schema, infoCase,
    } = this.state
    if (!sourceDsId || !sourceTableOrTopic || !targetDsId) return message.error('数据来源、数据表或数据源目标不能为空')
    this.setState({
      loading: true,
    })
    getCreateTableSql({
      dsId: sourceDsId, tableName: sourceTableOrTopic, targetDsId, schema: schema || '', infoCase,
    }).then((res) => {
      if (res.status === 200) {
        this.setState({
          scripts: res.data,
          isShows: true,
          loading: false,
        })
      } else {
        this.setState({
          loading: false,
        })
        message.error(res.msg)
      }
    })
  }

  /**
   * sql语句发生改变
   */
  valueChange = (scripts) => {
    this.setState({
      scripts,
    })
  };

  executeCreateTableSql = () => {
    executeCreateTableSql({
      dsId: this.state.targetDsId,
      scripts: this.state.scripts,
      }).then((res) => {
      if (res.status === 200) {
        this.setState({
          isShows: false,
        })

        if (res.data) {
          this.getTables(1, this.state.targetDsId, this.state.targetDsType, res.data.schema)
          this.form.current.setFieldsValue({
            // targetTable: res.data.tableName,
            targetTableOrTopic: res.data.tableName,
            targetSchema: res.data.schema,
          })
        }
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
    })
  }

  onConfirm = () => {
    this.form?.current?.validateFields().then(values => {
      this.props.currentStepChange(1, {
        ...values,
        sourceDsId: values.sourceDsId.split('_')[0],
        sourceDsType: values.sourceDsId.split('_')[1],
        targetDsId: values.targetDsId.split('_')[0],
        targetDsType: values.targetDsId.split('_')[1],
        start: values.start,
        jsContent: this.customEditorRef?.current?.getEditorValue() || '',
      })
    })
  }

  handlePreview = () => {
    const { sourceDsType, sourceDsId } = this.state
    const jsScript = this.customEditorRef?.current?.getEditorValue() || ''
    const values = this.form?.current?.getFieldsValue(true)
    this.setState({
      tableViewLoading: true,
    })
    previewDataForMq({
      anaysisType: Number(values.useJsFlag),
      mqType: sourceDsType,
      jsonContent: jsScript,
      fieldInfoList: values.fieldExpressRequests,
      topic: values.sourceTableOrTopic,
      dsId: sourceDsId,
    }).then((res) => {
      const data = res.data
      const tablePreview = []
      const tablePreviewColumn = []
      if (res.status === 200) {
        if (!data) return
        data[0]
          && data[0].map((item) => {
            tablePreviewColumn.push({
              title: item,
              dataIndex: item,
              key: item,
              width: 100,
              render: (txt) => (<div className={styles.td_ellipse} title={txt}>{txt}</div>),
            })
            return null
          })

        data.slice(1).map((item) => {
          const obj = {}
          data[0].map((val, key) => {
            obj[val] = `${item[key]}` // + ''  为了容错，后端返回的值为 对象类型
            return null
          })
          tablePreview.push(obj)
          return null
        })
        this.setState({
          tablePreview,
          tablePreviewColumn,
        })
        message.success(res.msg)
        this.form?.current?.setFieldsValue({
          tableData: data[0],
        })
      } else {
        message.error(res.msg)
      }
      this.setState({
        tableViewLoading: false,
      })
    })
  }

  save = () => {
    this.setState({
      loading: true,
    })
    const { data } = this.props
    this.form?.current?.validateFields().then(values => {
      onlineInsert({
        ...data,
        ...values,
        useJsFlag: Number(values.useJsFlag),
        sourceDsId: values.sourceDsId.split('_')[0],
        sourceDsType: values.sourceDsId.split('_')[1],
        targetDsId: values.targetDsId.split('_')[0],
        targetDsType: values.targetDsId.split('_')[1],
        start: values.start,
        jsContent: this.customEditorRef?.current?.getEditorValue() || '',
      }).then((res) => {
        if (res.status === 200) {
          message.success(res.msg)
          history.push('/dataIntegrate/sersync')
        } else {
          message.error(res.msg)
        }
        this.setState({
          loading: false,
        })
      })
    })
  }

  render() {
    const {
      useJsFlag, infoCase, sourceDs, targetDs, spinning, sourceTables, sourceSchema, isInfluxDBNew,
      targetSchema, targetTables, scripts, loading, previewData, targetDsType,
      sourceDsType, treeData, jsScript, fieldSuggestion, tableViewLoading, tablePreviewColumn, tablePreview,
    } = this.state
    const values = this.form.current?.getFieldsValue(true)
    return (
      <div className={styles.data_source} style={{ ...this.props.style }}>
        <Spin spinning={spinning}>
          <Form
            className={styles.form}
            colon={false}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            onValuesChange={this.valuesChange}
            ref={this.form}
          >
            <Item>
              <div className={styles.column}>基础设置</div>
            </Item>
            <Item
              label="任务名称"
              name="taskName"
              rules={[{ required: true, message: '请输入任务名称' }]}
            >
              <Input placeholder="请输入任务名称" />
            </Item>
            <Item
              label="目录"
              name="dirId"
              rules={[{ required: true, message: '请输入选择目录' }]}
            >
              <TreeSelect
                allowClear
                showSearch
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
                // dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={treeData}
                placeholder="请输入选择目录"
                treeDefaultExpandAll
                optionFilterProp="children"
                filterTreeNode={(input, treeNode) => treeNode.dirName.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                fieldNames={{
                  label: 'dirName', value: 'id', children: 'children',
                }}
              />
            </Item>
            <Item>
              <div className={styles.column}>数据来源</div>
            </Item>
            <Item
              label="数据来源"
              name="sourceDsId"
              rules={[{ required: true, message: '请选择数据来源' }]}
            >
              <Select
                showSearch
                filterOption={(input, option) => option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                optionFilterProp="title"
                allowClear
                placeholder="请选择数据来源"
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
              >
                {sourceDs && sourceDs.map((item) => (
                  <Option title={item.dsName} value={`${item.dsId}_${item.dsType}`} key={`${item.dsId}_${item.dsType}`}>
                    <div className={styles.source_name}>
                      {item.dsName}
                    </div>
                    <i
                      title={`${item.status ? '连接状态：正常' : '链接状态：失败'}`}
                      style={{ color: item.status ? '#43a047' : '#ef5350' }}
                      className={`iconfont ${item.status ? `icon-chenggong ${styles.chenggong}` : `icon-shibai1 ${styles.shibai}`}`}
                    />
                  </Option>
                ))}
              </Select>
            </Item>
            {sourceSchema && sourceSchema.length ? (
              <Form.Item
                label="schema"
                name="sourceSchema"
                rules={[{ required: true, message: '请选择schema' }]}
              >
                <Select
                  showSearch
                  optionFilterProp="title"
                  filterOption={(input, option) => option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  allowClear
                  placeholder="请选择schema"
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                >
                  {sourceSchema && sourceSchema.map((value) => (
                    <Option title={value} value={value}>
                      {value}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            ) : null}
            <div>
              {sourceDsType === 'MQTT' ? (
                <Item
                  label="Topic"
                  name="sourceTableOrTopic"
                  rules={[{ required: true, message: '请选择来源表' }]}
                >
                  <Input
                    allowClear
                    placeholder="请输入来源表"
                  />
                </Item>
              ) : (
                <Item
                  label={sourceDsType === 'Kafka' || sourceDsType === 'MQTT' ? 'Topic' : '来源表'}
                  name="sourceTableOrTopic"
                  rules={[{ required: true, message: '请选择来源表' }]}
                >
                  <Select
                    allowClear
                    placeholder="请选择来源表"
                    showSearch
                    filterOption={(input, option) => option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    optionFilterProp="title"
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  >
                    {sourceDsType === 'Kafka' ? sourceTables && sourceTables.map((item) => <Option disabled={(values?.sourceDsId === values?.targetDsId) && (values?.targetTableOrTopic === item)} title={item} value={item} key={item}>{item}</Option>) : sourceTables && sourceTables.map((item) => <Option title={item.schema ? `${item.schema}.${item.tableName}` : item.tableName} value={item.schema ? `${item.schema}.${item.tableName}` : item.tableName} key={item.schema ? `${item.schema}.${item.tableName}` : item.tableName}>{item.schema ? `${item.schema}.${item.tableName}` : item.tableName}</Option>)}
                  </Select>
                </Item>
              )}
              {sourceDsType === 'Kafka' || sourceDsType === 'MQTT' ? null : (
                <div
                  onClick={() => {
                    this.onlinePreviewData()
                  }}
                  className={styles.data_see}
                >数据预览
                </div>
              )}
            </div>
            {sourceDsType === 'Kafka' || sourceDsType === 'MQTT' ? (
              <div>
                <Item
                  noStyle
                  name="useJsFlag"
                  valuePropName="activeKey"
                  initialValue="0"
                >
                  <Tabs
                    destroyInactiveTabPane
                    onChange={(activeKey) => {
                      this.setState({
                        tablePreviewColumn: [],
                        tablePreview: [],
                        useJsFlag: Number(activeKey),
                      }, () => {
                        if (activeKey == 2) {
                          this.form.current.setFieldsValue({
                            targetDsId: null,
                          })
                        }
                        this.form.current.setFieldsValue({
                          fieldExpressRequests: [{
                            fieldName: '',
                            fieldExpress: '',
                          }],
                          tableData: null,
                        })
                      })
                    }}
                  >
                    <TabPane tab="默认" key="0" className={styles.tab_pane_height}>
                      <List
                        name="fieldExpressRequests"
                        initialValue={[{
                          varName: undefined,
                          varExpression: undefined,
                        }]}
                      >
                        {(fields, { add, remove }) => fields.map(({ key, name, ...restField }, index) => (
                          <Item
                            labelCol={index === 0 ? { span: 5 } : { span: 0 }}
                            wrapperCol={index === 0 ? { span: 19 } : { span: 19, offset: 5 }}
                            label={index === 0 ? (
                              <span>
                                结果变量名
                                <Popover
                                  content={
                                    <span>
                                      点击
                                      <span
                                        style={{ color: '#0084FF', cursor: 'pointer' }}
                                        onClick={() => {
                                          window.open(`${window.suanpan}Json.html`)
                                        }}
                                      >
                                        {' '}这里{' '}
                                      </span>
                                      查看Json解析说明
                                    </span>
                                  }
                                >
                                  <i className="iconfont icon-yiwentishi" />
                                </Popover>
                              </span>
                            ) : ''}
                            // required
                            key={key}
                          >
                            <div className={styles.parameter_item}>
                              <Item
                                name={[name, 'fieldName']}
                                noStyle
                                style={{ display: 'inline-block', width: 'calc(50% - 8px)' }}
                                rules={[
                                  // { required: true, message: '请输入结果变量名' },
                                  {
                                    pattern: new RegExp(lenRe.reg, 'g'),
                                    message: lenRe.text,
                                  },
                                ]}
                              >
                                <Input placeholder="请输入结果变量名" />
                              </Item>
                              <span className={styles.equal_sign}> = </span>
                              <Item
                                name={[name, 'fieldExpress']}
                                noStyle
                                rules={[
                                  // { required: true, message: '请输入结果表达式' },
                                  {
                                    pattern: new RegExp(lenRe.reg, 'g'),
                                    message: lenRe.text,
                                  },
                                ]}
                                style={{ display: 'inline-block', width: 'calc(50% - 8px)' }}
                              >
                                <AutoComplete
                                  type="text"
                                  autoComplete="off"
                                  placeholder="请输入结果表达式"
                                >
                                  {
                                    fieldSuggestion.map(item => (
                                      <Option key={item} value={item}>
                                        {item}
                                      </Option>
                                    ))
                                  }
                                </AutoComplete>
                              </Item>
                              <div className={styles.item_btn_wrap}>
                                {
                                  fields.length - 1 === index && <i className={`iconfont icon-tianjia1 ${styles.add_sign}`} onClick={() => add()} />
                                }
                                {
                                  fields.length - 1 !== 0 && <i className={`iconfont icon-shanchu ${styles.del_sign}`} onClick={() => remove(name)} />
                                }
                              </div>
                            </div>
                          </Item>
                        ))}
                      </List>
                    </TabPane>
                    <TabPane tab="自定义" key="1" className={styles.tab_pane_height}>
                      <div className={`${styles.api_bottom_out_example} ${styles.api_bottom_out_example_custom}`}>
                        <CreateDiffEditor
                          language="javascript"
                          theme="vs"
                          editorId={this.editorJsEditId}
                          ref={this.customEditorRef}
                          restData={jsScript || this.state.functionStr}
                        />
                      </div>
                    </TabPane>
                    <TabPane
                      tab={
                        <span>velocity
                          <Tooltip
                            placement="top"
                            title={
                              <div>
                                <p>IoTDB专用</p>
                                <p>{
                                  `说明：
                                  解析脚本遵循jsonpath和velocity语法，需要将jsonpath中代表根元素的$替换为&，见示例
                                  $iot、$IOT_DATA_MODEL为解析脚本保留字
                                  .setXXX(...)为方法调用
                                  支持的velocity解析方法如下：
                                  1.设置存储组名称 setStorageGroupDirect($IOT_DATA_MODEL,"name")
                                  2.设置存储组名称，jsonpath解析后得到 setStorageGroupFromJson($IOT_DATA_MODEL,"jsonpath")
                                  3.设置设备名称 setDeviceIdDirect($IOT_DATA_MODEL,"deviceName")
                                  4.设置设备名称，jsonpath解析后得到 setDeviceIdFromJson($IOT_DATA_MODEL,"jsonpath")
                                  5.设置时间戳，jsonpath解析后得到 setTimestampFromJson($IOT_DATA_MODEL,"jsonpath")
                                  6.指定日期格式，设置时间戳，jsonpath解析后得到 setTimestampFromJson($IOT_DATA_MODEL,"jsonpath","timeformat")
                                  7.设置测点值，jsonpath解析后得到 setMeasurementFromJson($IOT_DATA_MODEL,"jsonpath","idKey","valueKey")`
                                }
                                </p>
                              </div>
                            }
                          >
                            <i className="iconfont icon-yiwentishi" />
                          </Tooltip>
                        </span>
                      }
                      key="2"
                      className={styles.tab_pane_height}
                    >
                      <div className={`${styles.api_bottom_out_example} ${styles.api_bottom_out_example_custom}`}>
                        <CreateDiffEditor
                          language="velocity"
                          theme="vs"
                          editorId={`${this.editorJsEditId}velocity`}
                          ref={this.customEditorRef}
                          restData={jsScript || this.state.velocity}
                        />
                      </div>
                    </TabPane>
                  </Tabs>
                </Item>
                {useJsFlag != 2 ? (
                  <Item
                    className={styles.btn_wrap}
                    wrapperCol={{ span: 20, offset: 5 }}
                    label=""
                    colon={false}
                    name="varRelationship"
                  >
                    <Button type="primary" loading={tableViewLoading} onClick={this.handlePreview}>预览</Button>
                  </Item>
                ) : null}
                {useJsFlag != 2 ? (
                  <Item
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 19 }}
                    label="计算结果"
                    name="tableData"
                  >
                    <ProTable
                      loading={tableViewLoading}
                      rowKey={() => (Math.random())}
                      columns={tablePreviewColumn}
                      dataSource={tablePreview}
                      scroll={{ x: true, y: 110 }}
                      pagination={false}
                    />
                  </Item>
                ) : null}
              </div>
            ) : null}
            {
              sourceDsType === 'MySQL' || sourceDsType === 'Oracle' ? (
                <Item
                  label={
                    <span>采集起点
                      <Tooltip
                        placement="topRight"
                        title={
                          <div><p>Initial：从源头第一行数据开始采集</p>
                            <p>latest-offset：从当前提交任务开始采集数据</p>
                          </div>
                        }
                      ><i className="iconfont icon-yiwentishi" />
                      </Tooltip>
                    </span>
                  }
                  name="start"
                  rules={[{ required: true, message: '请选择采集起点' }]}
                >
                  <Radio.Group>
                    <Radio value={0}>initial</Radio>
                    <Radio value={1}>latest-offset</Radio>
                  </Radio.Group>
                </Item>
              ) : null
            }
            <Item>
              <div className={styles.column}>数据目标</div>
            </Item>
            <Item
              label={
                <span>数据目标
                  <Tooltip
                    placement="top"
                    title={
                      <div>
                        <p>来源是MQTT、Kafka的时候，使用velocity模板解析目标只能选择IoTDB</p>
                      </div>
                    }
                  >
                    <i className="iconfont icon-yiwentishi" />
                  </Tooltip>
                </span>
              }
              name="targetDsId"
              rules={[{ required: true, message: '请选择数据目标' }]}
            >
              <Select
                showSearch
                filterOption={(input, option) => option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                optionFilterProp="title"
                allowClear
                placeholder="请选择数据目标"
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
              >
                {targetDs && targetDs.map((item) => (
                  <Option disabled={useJsFlag == 2 && item.dsType !== 'IoTDB'} title={item.dsName} value={`${item.dsId}_${item.dsType}`} key={`${item.dsId}_${item.dsType}`}>
                    <div className={styles.source_name}>
                      {item.dsName}
                    </div>
                    <i
                      title={`${item.status ? '连接状态：正常' : '链接状态：失败'}`}
                      style={{ color: item.status ? '#43a047' : '#ef5350' }}
                      className={`iconfont ${item.status ? `icon-chenggong ${styles.chenggong}` : `icon-shibai1 ${styles.shibai}`}`}
                    />
                  </Option>
                ))}
              </Select>
            </Item>
            {targetSchema && targetSchema.length && useJsFlag != 2 ? (
              <Form.Item
                label="schema"
                name="targetSchema"
                rules={[{ required: true, message: '请选择schema' }]}
              >
                <Select
                  showSearch
                  optionFilterProp="title"
                  filterOption={(input, option) => option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  allowClear
                  placeholder="请选择schema"
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                >
                  {targetSchema && targetSchema.map((value) => (
                    <Option title={value} value={value}>
                      {value}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            ) : null}
            {useJsFlag != 2 && targetDsType !== 'InfluxDB' ? (
              <div className={styles.target_table}>
                {targetDsType === 'MQTT' ? (
                  <Item
                    label="Topic"
                    name="targetTableOrTopic"
                    rules={[{ required: true, message: '请输入Topic' }]}
                  >
                    <Input
                      allowClear
                      placeholder="请输入Topic"
                    />
                  </Item>
                ) : (
                  <Item
                    label={targetDsType === 'Kafka' || targetDsType === 'MQTT' ? 'Topic' : '目标表'}
                    name="targetTableOrTopic"
                    rules={[{ required: true, message: '请选择目标表' }]}
                  >
                    <Select
                      allowClear
                      placeholder="请选择目标表"
                      showSearch
                      filterOption={(input, option) => option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      optionFilterProp="title"
                      getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    >
                      {targetDsType === 'Kafka' ? targetTables && targetTables.map((item) => <Option disabled={(values?.sourceDsId === values?.targetDsId) && (values?.sourceTableOrTopic === item)} title={item} value={item} key={item}>{item}</Option>) : targetTables && targetTables.map((item) => <Option title={item.schema ? `${item.schema}.${item.tableName}` : item.tableName} value={item.schema ? `${item.schema}.${item.tableName}` : item.tableName} key={item.schema ? `${item.schema}.${item.tableName}` : item.tableName}>{item.schema ? `${item.schema}.${item.tableName}` : item.tableName}</Option>)}
                    </Select>
                  </Item>
                )}
                {targetDsType === 'MQTT' ? null : (
                  <Button
                    loading={loading}
                    onClick={() => {
                      this.getCreateTableSql()
                    }}
                    className={styles.target_table_clear}
                    style={{ float: 'right' }}
                  >一键建表
                  </Button>
                )}
              </div>
            ) : null}
            {
              (useJsFlag != 2 && targetDsType === 'InfluxDB') && (
                <>
                  <Item
                    label="是否新建表"
                    name="isInfluxDBNew"
                    initialValue
                  >
                    <Select
                      placeholder="是否新建表"
                      getPopupContainer={(triggerNode) => triggerNode.parentNode}
                      value={isInfluxDBNew}
                      onChange={(e) => this.setState({ isInfluxDBNew: e })}
                    >
                      <Option value={false}>不存在，新建</Option>
                      <Option value>已存在，不新建</Option>
                    </Select>
                  </Item>
                  {
                    isInfluxDBNew ? (
                      <Item
                        label="目标表"
                        name="targetTableOrTopic"
                        rules={[{ required: true, message: '请选择目标表' }]}
                      >
                        <Select
                          allowClear
                          placeholder="请选择目标表"
                          showSearch
                          filterOption={(input, option) => option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                          optionFilterProp="title"
                          getPopupContainer={(triggerNode) => triggerNode.parentNode}
                        >
                          {
                            targetTables && targetTables.map(
                              (item) =>
                                (<Option
                                  title={item.schema ? `${item.schema}.${item.tableName}` : item.tableName}
                                  value={item.schema ? `${item.schema}.${item.tableName}` : item.tableName}
                                  key={item.schema ? `${item.schema}.${item.tableName}` : item.tableName}
                                >
                                  {item.schema ? `${item.schema}.${item.tableName}` : item.tableName}
                                </Option>),
                            )
                          }
                        </Select>
                      </Item>
                    ) : (
                      <Item
                        label="目标表"
                        name="targetTableOrTopic"
                        rules={[{ required: true, message: '请输入目标表名称' }]}
                      >
                        <Input placeholder="请输入目标表名称" />
                      </Item>
                    )
                  }
                </>
              )
            }
          </Form>
          <div className={styles.edit_footer}>
            <Button onClick={() => { history.push('/dataIntegrate/sersync') }} className={styles.edit_btn}>取消</Button>
            {targetDsType === 'Kafka' && sourceDsType !== 'Mongodb' || targetDsType === 'MQTT' || useJsFlag == 2 ? (
              <Button
                className={styles.edit_btn}
                type="primary"
                loading={loading}
                onClick={this.save}
              >确认
              </Button>
            ) : (
              <Button
                className={styles.edit_btn}
                type="primary"
                onClick={this.onConfirm}
              >下一步
              </Button>
            )}
          </div>
          <Modal
            destroyOnClose
            title="一键建表"
            width="8.5rem"
            visible={this.state.isShows}
            confirmLoading={this.state.confirmLoading}
            onOk={() => {
              this.executeCreateTableSql()
            }}
            onCancel={() => {
              this.setState({
                isShows: false,
              })
            }}
          >
            <Spin spinning={loading}>
              <div className={styles.CreateDiff_Editor_Modal}>
                <Row gutter={100}>
                  <Col span={12}>
                    <Radio.Group
                      style={{ paddingBottom: '.2rem' }}
                      onChange={(e) => {
                        this.setState({
                          infoCase: e.target.value,
                        }, () => {
                          this.getCreateTableSql()
                        })
                      }}
                      value={infoCase}
                    >
                      <Radio value={1}>原表保持一致</Radio>
                      <Radio value={2}>全部大写</Radio>
                      <Radio value={3}>全部小写</Radio>
                    </Radio.Group>
                  </Col>
                </Row>
                <CreateDiffEditor
                  restData={scripts && sqlFormatter.format(scripts) || ''}
                  // ref={(dev) => {
                  //   this.shellEditorRef = dev
                  // }}
                  valueChange={this.valueChange}
                  language="sql"
                  editorId="data-target-editor"
                />
              </div>
            </Spin>
          </Modal>
          <Modal
            destroyOnClose
            title="数据预览"
            width="7rem"
            visible={this.state.dataShows}
            confirmLoading={this.state.confirmLoading}
            bodyStyle={{
              maxHeight: `${document.documentElement.clientHeight * 0.65}px`,
              overflowY: 'auto',
            }}
            onOk={() => {
              this.setState({
                dataShows: false,
              })
            }}
            onCancel={() => {
              this.setState({
                dataShows: false,
              })
            }}
            footer={false}
          >
            <div className={styles.CreateDiff_Editor_Modal}>
              <ProTable
                pagination={false}
                columns={previewData.columns}
                dataSource={previewData.data}
                scroll={{ x: 700 }}
                emptyText="暂无数据"
              />
            </div>
          </Modal>
        </Spin>
      </div>
    )
  }
}

export default DataSource
